import { queryConfigBykey, saveConfig } from "@/api/config";
import { HOME_TEXT_KEY } from "@/constants/configKey.constant";
import { ConfigType } from "@/types/config";
import { message } from "antd";
import { useForm } from "antd/es/form/Form";
import { useState, useCallback, useEffect } from "react";

export type FieldType = {
    title: string;
    printText: string;
  };
export const useHomeText = ()=>{
    const [loading, setLoading] = useState(false);
    const [btnLoading, setBtnLoading] = useState(false);
    const [messageApi] = message.useMessage();
    const [form] = useForm()
  
    const [configInfo,setConfigInfo]= useState<ConfigType.Row<FieldType> >({
      id: "",
      title: "",
      configKey: "",
      config: "",
    })
    const getConfig = useCallback(async () => {
      setLoading(true);
      const res = await queryConfigBykey(HOME_TEXT_KEY);
      setLoading(false);
      if (res.code === 200) {
        const obj = res.data || {};
        const config = obj.config ? JSON.parse(obj.config) : {};
        setConfigInfo({
          id:obj.id,
          title: obj.title,
          configKey: obj.configKey,
          config,
        });
        form.setFieldsValue({
          title:config.title||'',
          printText:config.printText||''
        })
      }
    },[form])
  
    /**
     * 保存配置
     * @param config
     */
    const saveConfigInf = async (values:FieldType) => {
      const { title, printText } = values;
      const config = {
        title,
        printText,
      };
      const params = {
        id: configInfo?.id,
        configKey: HOME_TEXT_KEY,
        config: JSON.stringify(config),
      };
      setBtnLoading(true);
      const res = await saveConfig(params);
      setBtnLoading(false);
      if (res.code === 200) {
        messageApi.success("保存成功");
        getConfig();
      }
    };
    const onFinish = async (values: FieldType) => {
      saveConfigInf(values);
    };
    useEffect(()=>{
      getConfig()
    },[getConfig])
    return {
        loading,
        form,
        btnLoading,
        onFinish
    }
}